﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using StateGrid;
using StateGrid.GJIBZ;
using StateGrid.User;
using StateGrid.GlobalVariables;
using iTextSharp.text.pdf;
using StateGrid.OperationLog;

public partial class AddPM : System.Web.UI.Page
{
    /// <summary>
    /// 国际标准操作对象
    /// </summary>
    private GJIBZ_DAO gjibzDAO = new GJIBZ_DAO();

    /// <summary>
    /// 日志操作对象
    /// </summary>
    private OperationLog_DAO operationLogDAO = new OperationLog_DAO();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!UserManageDAO.IsLogin((User)Session["login"]))
        {
            GlobalMethod.RedirectLogin(Response);
            return;
        }

        if (!this.IsPostBack)
        {
            this.BindData();
        }

    }

    /// <summary>
    /// 绑定初始化数据
    /// </summary>
    private void BindData()
    {
        String message = null;
        String bzwh = HttpUtility.UrlDecode(Request["bzwh"]);
        if (null == bzwh || "".Equals(bzwh))
        {
            message = "错误： 参数错误";
            Response.Redirect(GlobalResource.ERROR_PAGE + "?message=" + message);
            return;
        }

        //存在多个标准文号时，只显示最后一个
        String[] bzwhs = bzwh.Split(';');
        bzwh = bzwhs[bzwhs.Length - 1];

        GJIBZ_PM gjibzPM = this.gjibzDAO.GetGJIBZ_PMByBzwh(bzwh);

        if (null == gjibzPM)
        {
            message = "错误：没有找到该标准文号";
            Response.Redirect(GlobalResource.ERROR_PAGE + "?message=" + message);
            return;
        }

        //获取对应分类
        GJIBZ_FL gjibzFL = this.gjibzDAO.GetGJIBZ_FLByFlbm(gjibzPM.flbm);
        //设置返回按钮链接
        this.backHyperLink.NavigateUrl = GlobalGJIBZ.LISTPM_PAGE + "?catalog=" + gjibzFL.flbm;

        User user = (User)Session["login"];
        //登陆超时则退到登录页
        if (null == user)
        {
            Response.Write(" <script> top.location = '" + GlobalResource.LOGIN_PAGE + "' </script> ");
            return;
        }
        //登录人
        this.dlrTextBox.Text = user.name;

        //分类编码
        this.flbmTextBox.Text = gjibzFL.flbm;
        //分类名称
        this.flmcTextBox.Text = gjibzFL.flmc;
        //标准文号
        this.bzwhTextBox.Text= gjibzPM.bzwh;
        //实施年份
        String[] bz = bzwh.Split('-');
        this.ssnfTextBox.Text = bz[bz.Length-1];

        //版本性质
        this.bbxzTextBox.Text = gjibzPM.bbxz;
        //中文名称
        this.zwmcTextBox.Text = gjibzPM.zwmc;
        //外文名称
        this.wwmcTextBox.Text = gjibzPM.wwmc;
        //ICS分类
        this.icsflTextBox.Text = gjibzPM.icsfl;
        //GB分类
        this.gbflTextBox.Text = gjibzPM.gbfl;

        if (null != gjibzPM.fbrq && !"".Equals(gjibzPM.fbrq))
        {
            DateTime dt = (DateTime)gjibzPM.fbrq;
            this.fbrqTextBox.Text = dt.ToString("yyyy-MM-dd");//发布日期
        }
        if (null != gjibzPM.ssrq && !"".Equals(gjibzPM.ssrq))
        {
            DateTime dt = (DateTime)gjibzPM.ssrq;
            this.ssrqTextBox.Text = dt.ToString("yyyy-MM-dd");//实施日期
        }
        this.dtbzTextBox.Text = gjibzPM.dtbz;//代替标准
        this.bdtbzTextBox.Text =gjibzPM.bdtbz;//被代替标准
        this.zfCheckBox.Checked = gjibzPM.zf;//作废
        this.zfnfTextBox.Text = gjibzPM.zfnf;//作废年份
        this.cygxTextBox.Text = gjibzPM.cygx; //采用关系
        this.ysTextBox.Text = gjibzPM.ys.ToString();//页数
        this.zwztcTextBox.Text = gjibzPM.zwztc;//中文主题词
        this.wwmcTextBox.Text = gjibzPM.wwztc;//外文主题词
        this.bzTextBox.Text = gjibzPM.bz;//备注
        this.gxxTextBox.Text = gjibzPM.gxx;//更新项

        //文件名
        this.pdfHyperLink.Text = gjibzPM.wjm;
        this.pdfHyperLink.NavigateUrl = GlobalResource.VIEW_PAGE + "?fileName=" + gjibzPM.wjm;
    }

    /// <summary>
    /// 获取用户填写的国际标准篇名信息
    /// </summary>
    /// <returns></returns>
    private GJIBZ_PM GetGJIBZPM()
    {
        GJIBZ_PM gjibzPM = new GJIBZ_PM();
        //标准文号
        gjibzPM.bzwh = this.bzwhTextBox.Text.Trim();
        //分类编码
        gjibzPM.flbm = this.flbmTextBox.Text;
        //文件名
        gjibzPM.wjm = this.pdfHyperLink.Text;
        //中文名称
        gjibzPM.zwmc = this.zwmcTextBox.Text.Trim();
        //版本性质
        gjibzPM.bbxz = this.bbxzTextBox.Text.Trim();
        //ICS分类
        gjibzPM.icsfl = this.icsflTextBox.Text.Trim();
        //GB分类
        gjibzPM.gbfl = this.gbflTextBox.Text.Trim();
        //外文名称
        gjibzPM.wwmc = this.wwmcTextBox.Text.Trim();
        //发布日期
        if (!"".Equals(this.fbrqTextBox.Text))
        {
            gjibzPM.fbrq = DateTime.Parse(this.fbrqTextBox.Text);
        }
        //实施日期
        if (!"".Equals(this.ssrqTextBox.Text))
        {
            gjibzPM.ssrq = DateTime.Parse(this.ssrqTextBox.Text);
        }
        //采用关系
        gjibzPM.cygx = this.cygxTextBox.Text.Trim();
        //代替标准
        gjibzPM.dtbz = this.dtbzTextBox.Text.Trim();
        //被代替标准
        gjibzPM.bdtbz = this.bdtbzTextBox.Text.Trim();
        //页数
        if (!"".Equals(this.ysTextBox.Text))
            gjibzPM.ys = Int32.Parse(this.ysTextBox.Text);
        //作废
        gjibzPM.zf = this.zfCheckBox.Checked;
        //作废年份
        gjibzPM.zfnf = this.zfnfTextBox.Text.Trim();
        //中文主题词
        gjibzPM.zwztc = this.zwmcTextBox.Text.Trim();
        //外文主题词
        gjibzPM.wwztc = this.wwztcTextBox.Text.Trim();
        //备注
        gjibzPM.bz = this.bzTextBox.Text.Trim();
        //更新项
        gjibzPM.gxx = this.gxxTextBox.Text.Trim();
        //更新日期
        gjibzPM.gxrq = DateTime.Now;
        //登录人
        gjibzPM.dlr = this.dlrTextBox.Text.Trim();

        return gjibzPM;
    }

    protected void submitButton_Click(object sender, EventArgs e)
    {
        //验证中文名称
        if (!this.ValidateZWMC())
        {
            return;
        }
        //验证实施日期
        if (!this.ValidateSSRQ())
        {
            return;
        }
        //验证发布日期
        if (!this.ValidateFBRQ())
        {
            return;
        }
        //验证页数
        if (!this.ValidateYS())
        {
            return;
        }
        //验证上传文件
        if (!this.ValidateYWJMFileUpload())
        {
            return;
        }

        //验证代替标准
        if (!this.ValidateDTBZ(this.dtbzTextBox.Text))
        {
            return;
        }

        //验证被代替标准
        if (!this.ValidateDTBZ(this.bdtbzTextBox.Text))
        {
            return;
        }

        GJIBZ_PM gjibzPM = this.GetGJIBZPM();
        if ( null != this.ywjmFileUpload.FileName && !"".Equals(this.ywjmFileUpload.FileName))
        {
            if (!OperationFile.Upload(this.ywjmFileUpload, gjibzPM.wjm))
            {
                Response.Write("<Script>alert('更新国际标准信息失败')</Script>");
                return;
            }
        }

        if (this.gjibzDAO.UpdateGJIBZ_PM(gjibzPM, ((User)Session["login"]).name))
        {
            Response.Write("<Script>alert('更新国际标准信息成功')</Script>");
            if (!"".Equals(this.dtbzTextBox.Text))
                this.UpdateTdbz(this.dtbzTextBox.Text, this.bzwhTextBox.Text);
            if (!"".Equals(this.bdtbzTextBox.Text))
                this.UpdateBtdbz(this.bdtbzTextBox.Text, this.bzwhTextBox.Text);

            this.BindData();
        }
        else
                Response.Write("<Script>alert('更新国际标准信息失败')</Script>");

    }

    //更新被替代标准信息
    private void UpdateBtdbz(String bzs, String bzwh)
    {
        String[] str = bzs.Split(';');
        for (int i = 0; i < str.Length; i++)
        {
            GJIBZ_PM gjibzPM = this.gjibzDAO.GetGJIBZ_PMByBzwh(str[i]);
            if (gjibzPM == null) continue;

            if (null == gjibzPM.dtbz || "".Equals(gjibzPM.dtbz))
                gjibzPM.dtbz = bzwh;
            else if (gjibzPM.dtbz.IndexOf(bzwh) < 0)//原被替代标准关系中不存在，则加上
            {
                gjibzPM.dtbz = gjibzPM.dtbz + ";" + bzwh;
            }

            //进行更新
            this.gjibzDAO.UpdateGJIBZ_PM(gjibzPM, ((User)Session["login"]).name);
        }
    }

    //更新替代标准信息
    private void UpdateTdbz(String bzs, String bzwh)
    {
        String[] str = bzs.Split(';');
        for (int i = 0; i < str.Length; i++)
        {
            GJIBZ_PM gjibzPM = this.gjibzDAO.GetGJIBZ_PMByBzwh(str[i]);
            if (gjibzPM == null) continue;

            gjibzPM.zf = true;
            if (null == gjibzPM.bdtbz || "".Equals(gjibzPM.bdtbz))
                gjibzPM.bdtbz = bzwh;
            else if (gjibzPM.bdtbz.IndexOf(bzwh) < 0)//原被替代标准关系中不存在，则加上
            {
                gjibzPM.bdtbz = gjibzPM.bdtbz + ";" + bzwh;
            }
            //作废年份为更新标准的年份
            String[] bnf = bzwh.Split('-');
            gjibzPM.zfnf = bnf[bnf.Length - 1];

            //进行更新
            this.gjibzDAO.UpdateGJIBZ_PM(gjibzPM, ((User)Session["login"]).name);
        }
    }

    /// <summary>
    /// 验证中文名称
    /// </summary>
    /// <returns></returns>
    private Boolean ValidateZWMC()
    {
        Boolean flag = true;

        this.errorLabel.Text = "";
        if(null==this.zwmcTextBox.Text||"".Equals(this.zwmcTextBox.Text.Trim()))
        {
            this.errorLabel.Text = "错误：中文名称不能为空";
            flag = false;
        }
        return flag;
    }

    /// <summary>验证发布日期</summary>
    private Boolean ValidateFBRQ()
    {
        this.errorLabel.Text = "";

        Boolean flag = true;
        if (this.fbrqTextBox != null && this.fbrqTextBox.Text != "")
        {
            try
            {
                DateTime val = DateTime.Parse(this.fbrqTextBox.Text);
            }
            catch (Exception)
            {
                this.errorLabel.Text = "错误：发布日期格式不正确(yyyy-MM-dd)";
                return false;
            }
        }

        return flag;
    }

    /// <summary>验证实施日期</summary>
    private Boolean ValidateSSRQ()
    {
        this.errorLabel.Text = "";

        Boolean flag = true;
        if (this.ssrqTextBox != null && this.ssrqTextBox.Text != "")
        {
            try
            {
                DateTime val = DateTime.Parse(this.ssrqTextBox.Text);
                String nf = val.Year.ToString();
                if (!nf.Equals(this.bzwhTextBox.Text.Split('-')[1])) {
                    this.errorLabel.Text ="错误：标准文号的年份与实施年份不符";
                    return false;
                }
            }
            catch (Exception)
            {
                this.errorLabel.Text = "错误：实施日期格式不正确(yyyy-MM-dd)";
                return false;
            }
        }

        return flag;
    }

    /// <summary>验证页数</summary>
    private Boolean ValidateYS()
    {
        this.errorLabel.Text = "";

        Boolean flag = true;
        if (this.ysTextBox != null && this.ysTextBox.Text != "")
        {
            try
            {
                int val = Int32.Parse(this.ysTextBox.Text);
            }
            catch (Exception)
            {
                this.errorLabel.Text = "错误：页数信息不是有效数字";
                return false;
            }
        }

        return flag;
    }
    ///<summary>验证代替标准是否存在</summary>
    private Boolean ValidateDTBZ(String dtbz)
    {
        Boolean flag = true;
        if (null == dtbz || "".Equals(dtbz)) return flag;

        String[] bzs = dtbz.Split(';');
        for (int i = 0; i < bzs.Length; i++)
        {
            GJIBZ_PM gjibz = this.gjibzDAO.GetGJIBZ_PMByBzwh(bzs[i]);
            if (null == gjibz)
            {
                this.errorLabel.Text = "错误：该代替标准("+ bzs[i] + ")不存在，请核实";
                return false;
            }
        }

        return flag;
    }

    ///<summary>构造出文件名</summary>
    ///<param name="bzwh">标准文号</param>
    ///<param name="bbxz>版本性质</param>
    private String ConstructWJM(String bzwh, String bbxz)
    {
        String wjm = null;
        int times = 0;

        for (int i = 0; i < bzwh.Length; i++)
        {
            //第一个空格
            if (bzwh[i] == ' ' && times == 0)
            {
                wjm = wjm + "_";//替换空格
                if (null != bbxz && !"".Equals(bbxz)) bbxz = bbxz + "_";
                wjm = wjm + bbxz;//连接版本性质
                times = 1;
                continue;
            }

            if (bzwh[i] == ' ' && times > 0)
            {
                wjm = wjm + "_";
                continue;
            }

            if (bzwh[i] == '.')
            {
                wjm = wjm + "~";
                continue;
            }

            wjm = wjm + bzwh[i];
        }

        wjm = wjm + ".PDF";

        return wjm;
    }
    /// <summary>
    /// 验证上传文件
    /// </summary>
    /// <returns></returns>
    private Boolean ValidateYWJMFileUpload()
    {
        this.errorLabel.Text = "";
        Boolean flag = true;
        if (null == this.ywjmFileUpload || !this.ywjmFileUpload.HasFile)
        {
        }
        else
        {
            if (!this.ywjmFileUpload.FileName.EndsWith(".PDF", true, null))
            {
                this.errorLabel.Text = "错误：请选择PDF类型文件";
                flag = false;
            }
            else
            {
                PdfReader pdf = new PdfReader(this.ywjmFileUpload.FileBytes);
                if (null != pdf)
                {
                    //文件大小不能超过10M
                    if (pdf.FileLength >= 10 * 1024 * 1024)
                    {
                        this.errorLabel.Text = "错误：选择的文件大小超过了10M";
                        pdf.Close();
                        return false;
                    }

                    this.ysTextBox.Text = pdf.NumberOfPages.ToString();
                    if (null != this.pdfHyperLink.Text && !"".Equals(this.pdfHyperLink.Text))
                    {
                    }
                    else
                        this.pdfHyperLink.Text = ConstructWJM(this.bzwhTextBox.Text, this.bbxzTextBox.Text);
                }

                pdf.Close();
            }
        }
        return flag;
    }

    //全角转半角
    protected void resetButton_Click(object sender, EventArgs e)
    {
        this.BindData();
    }
    protected void icsflTextBox_TextChanged(object sender, EventArgs e)
    {
        this.icsflTextBox.Text = GlobalMethod.Semicolon(this.icsflTextBox.Text.Trim());
    }
    protected void gbflTextBox_TextChanged(object sender, EventArgs e)
    {
        this.gbflTextBox.Text = GlobalMethod.Semicolon(this.gbflTextBox.Text.Trim());
    }
    protected void zwztcTextBox_TextChanged(object sender, EventArgs e)
    {
        this.zwztcTextBox.Text = GlobalMethod.Semicolon(this.zwztcTextBox.Text.Trim());
    }
    protected void wwztcTextBox_TextChanged(object sender, EventArgs e)
    {
        this.wwztcTextBox.Text = GlobalMethod.Semicolon(this.wwztcTextBox.Text.Trim());
    }
    protected void dtbzTextBox_TextChanged(object sender, EventArgs e)
    {
        this.dtbzTextBox.Text = GlobalMethod.Semicolon(this.dtbzTextBox.Text.Trim());
    }
    protected void bdtbzTextBox_TextChanged(object sender, EventArgs e)
    {
        this.bdtbzTextBox.Text = GlobalMethod.Semicolon(this.bdtbzTextBox.Text.Trim());
    }
}